//
//  SearchVC.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/30.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "SearchVC.h"
#import "SearchRecommendCell.h"
#import "SearchHistoryCell.h"
#import "PlanVM.h"
#import "MyVM.h"
#import "PlanPeopleVC.h"
@interface SearchVC ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UIView            *navView;
@property (nonatomic ,strong) UISearchBar       *searchBar;
@property (nonatomic ,strong) UITableView       *tableView;
@property (nonatomic ,strong) NSMutableArray    *historyArr;
@property (nonatomic ,strong) NSMutableArray    *hotArr;
@property (nonatomic ,strong) NSMutableArray    *searchArr;

@end

@implementation SearchVC{
    BOOL    isSearch;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getHistory];
    [self getHotExperts];
    self.navigationItem.titleView=self.searchBar;
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancle)];
    self.navigationItem.rightBarButtonItem=rightItem;
    [self.tableView reloadData];
    // Do any additional setup after loading the view.
    
    
}

- (void)cancle{
    if (isSearch==NO&&self.searchBar.text.length==0) {
        [self backClick];
        return;
    }
    isSearch=NO;
    self.searchBar.text=@"";
    [self.searchBar resignFirstResponder];
    [self footerView:YES];
    [self.tableView reloadData];
}

#pragma mark -- 获取热搜专家
- (void)getHotExperts{
    WS(weakSelf);
    [[PlanVM manage] getExpertHotList:self.lType andTop:5 WithSuccess:^(id returnValue) {
        weakSelf.hotArr=returnValue;
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma marl -- 历史搜索记录
- (void)getHistory{
    WS(weakSelf);
    [[PlanVM manage] getHistoryListWithLtype:self.lType WithSuccess:^(id returnValue) {
        weakSelf.historyArr=returnValue;
        if (weakSelf.historyArr.count>0) {
            [weakSelf footerView:YES];
        }
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 取消关注
- (void)cancleFouse:(ExpertsHotModel *)model{
    WS(weakSelf);
    [[MyVM manage] cancleFollowWithId:model.UserId Success:^(id returnValue) {
        [SVProgressHUD showSuccessWithStatus:@"取消成功"];
        model.isFollow=NO;
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 关注
- (void)addFouse:(ExpertsHotModel *)model{
    WS(weakSelf);
    [[MyVM manage] addFollowWithId:model.UserId Success:^(id returnValue) {
        [SVProgressHUD showSuccessWithStatus:@"关注成功"];
        model.isFollow=YES;
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 清空历史记录
- (void)onclickClean{
    WS(weakSelf);
    [[PlanVM manage] deleteHistoryWithUid:@"0" WithLtype:self.lType WithSuccess:^(id returnValue) {
        [weakSelf.historyArr removeAllObjects];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 删除某条历史记录
- (void)deleteHistory:(ExpertsHotModel *)model{
    WS(weakSelf);
    [[PlanVM manage] deleteHistoryWithUid:model.UserId WithLtype:self.lType WithSuccess:^(id returnValue) {
        [weakSelf.historyArr removeObject:model];
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (isSearch) {
        return 1;
    }
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        if (isSearch) {
            return self.searchArr.count;
        }
        return self.hotArr.count;
    }
    return self.historyArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        
        return 30;
    }
    return 25;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        UIView *topView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        topView.backgroundColor=[UIColor whiteColor];
        if (isSearch) {
            QXLable *labPrompt=[[QXLable alloc]init];
            labPrompt.text=@"搜索结果";
            [topView addSubview:labPrompt];
            [labPrompt mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(topView).with.offset(10);
                make.centerY.equalTo(topView);
            }];
            return topView;
        }
        UIImageView *fireImage =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"fire"]];
        [topView addSubview:fireImage];
        [fireImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(topView);
            make.left.equalTo(topView).with.offset(10);
            make.size.mas_equalTo(fireImage.image.size);
        }];
        
        QXLable *lab=[[QXLable alloc]init];
        NSMutableAttributedString *attStr=[[NSMutableAttributedString alloc]initWithString:@"专家热搜榜 实时更新"];
        [attStr addAttribute:NSForegroundColorAttributeName value:DEFAULTTEXTGRAYCOLOR range:NSMakeRange(5, attStr.length-5)];
        [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(5, attStr.length-5)];
        lab.attributedText=attStr;
        [topView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(fireImage.mas_right).with.offset(10);
            make.centerY.equalTo(topView);
            make.size.mas_equalTo(CGSizeMake(150, 30));
        }];
        return topView;
    }else{
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, real_size(10))];
        view.backgroundColor=DEFAULTBGCOLOR;
        QXLable *lab=[[QXLable alloc]initWithFount:13];
        lab.text=@"历史搜索";
        [view addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).with.offset(10);
            make.top.bottom.equalTo(view);
            make.width.mas_equalTo(@100);
        }];
        return view;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        SearchRecommendCell *cell =[tableView  dequeueReusableCellWithIdentifier:@"SearchRecommendCell" forIndexPath:indexPath];
        if (isSearch) {
            cell.model=self.searchArr[indexPath.row];
        }else{
            cell.model=self.hotArr[indexPath.row];
        }
        
        WS(weakSelf);
        cell.focusBlock = ^(ExpertsHotModel *model) {
            if (model.isFollow) {
                [weakSelf cancleFouse:model];
            }else{
                [weakSelf addFouse:model];
            }
        };
        return cell;
    }
    
    
    SearchHistoryCell *cell=[tableView dequeueReusableCellWithIdentifier:@"SearchHistoryCell" forIndexPath:indexPath];
    cell.model=self.historyArr[indexPath.row];
    WS(weakSelf);
    cell.deleteBlock = ^(ExpertsHotModel *model) {
        [weakSelf deleteHistory:model];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    ExpertsHotModel *model;
    if (indexPath.section==0) {
        if (isSearch) {
            model=self.searchArr[indexPath.row];
        }else{
            model=self.hotArr[indexPath.row];
        }
        [[PlanVM manage] insterHistoryWithUid:model.UserId WithLtype:self.lType];
    }else{
        model=self.historyArr[indexPath.row];
    }
    ExpertsModel *eModel=[[ExpertsModel alloc]init];
    eModel.UserId=model.UserId;
    eModel.Avater=model.Avater;
    eModel.lType=model.lType;
    PlanPeopleVC *vc=[[PlanPeopleVC alloc]init];
    vc.lotteryModel=self.lotteryModel;
    vc.model=eModel;
//    vc.playArr=self.playArr;
    [self.navigationController pushViewController:vc animated:YES];
}



#pragma mark --UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    WS(weakSelf);
    [[PlanVM manage] searchExperWithLtype:self.lType andNickName:searchBar.text WithSuccess:^(id returnValue) {
        isSearch=YES;
        [weakSelf footerView:NO];
        weakSelf.searchArr=returnValue;
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]init];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.rowHeight=UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight=60;
        _tableView.backgroundColor=DEFAULTBGCOLOR;
        [_tableView registerClass:[SearchRecommendCell class] forCellReuseIdentifier:@"SearchRecommendCell"];
        [_tableView registerClass:[SearchHistoryCell class] forCellReuseIdentifier:@"SearchHistoryCell"];
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(self.view).with.offset(2);
        }];
    }
    return _tableView;
}

- (void)footerView:(BOOL)isShow{
    if (isShow) {
        QXLable *lab=[[QXLable alloc]initCenterTextWithText:@"清空历史"];
        lab.backgroundColor=[UIColor whiteColor];
        lab.frame=CGRectMake(0, 0, SCREEN_WIDTH, 40);
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onclickClean)];
        [lab addGestureRecognizer:tap];
        lab.userInteractionEnabled=YES;
        _tableView.tableFooterView=lab;
    }else{
        _tableView.tableFooterView=nil;
    }
    
}

- (UISearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        _searchBar.placeholder=@"请输入专家名称";
        _searchBar.delegate=self;
        [_searchBar setBackgroundImage:[TGTools createImageWithColor:[UIColor clearColor]]];
        _searchBar.showsCancelButton=NO;
        [[[_searchBar.subviews objectAtIndex:0].subviews objectAtIndex:1] setTintColor:DEFAULTBGCOLOR];
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.backgroundColor = [UIColor whiteColor];
        searchField.textColor = DEFAULTTEXTBLACKCOLOR;
        searchField.font = [UIFont systemFontOfSize:15];
        if (@available(iOS 11.0, *)) {
            [[_searchBar.heightAnchor constraintEqualToConstant:44.0] setActive:YES];
            // 查看视图层级，在iOS 11之前searchbar的x是12
            searchField.frame = CGRectMake(12, 8, SCREEN_WIDTH*0.8, 28);
        } else {
            searchField.frame = CGRectMake(0, 8, SCREEN_WIDTH*0.8, 28);
        }
        searchField.borderStyle = UITextBorderStyleNone;
        searchField.layer.cornerRadius = 5;
        searchField.layer.masksToBounds = YES;
        [_searchBar setValue:searchField forKey:@"searchField"];
        _searchBar.searchTextPositionAdjustment = (UIOffset){10, 0}; //
    }
    return _searchBar;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
